package cn.com.utt.gateway.controller;

import java.security.Principal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import cn.com.utt.unms.pojo.Group;
import cn.com.utt.unms.pojo.Log;
import cn.com.utt.common.log.SaveIpaddress;
import cn.com.utt.common.service.RoleService;
import cn.com.utt.common.service.TableService;
import cn.com.utt.common.service.UserRoleService;
import cn.com.utt.common.service.UserService;
import cn.com.utt.common.util.LocaleMessageSourceUtil;
import cn.com.utt.common.util.Tips;
import cn.com.utt.common.vo.OrderColumn;
import cn.com.utt.common.vo.RestResult;
import cn.com.utt.common.vo.Role;
import cn.com.utt.common.vo.TableCustomColumn;
import cn.com.utt.common.vo.User;
import cn.com.utt.common.vo.UserRole;
import cn.com.utt.unms.service.GroupService;
import cn.com.utt.unms.service.LogService;

@RestController
@RequestMapping("v1/users")
public class UserController {
	
	@Autowired
    private LocaleMessageSourceUtil messageSourceUtil;

	@Autowired
	private TableService tableService;

	@Autowired
	private UserService userService;

	@Autowired
	private GroupService groupService;

	@Autowired
	private UserRoleService userRoleService;

	@Autowired
	private RoleService roleService;

	@Autowired
	private LogService logService;

	@RequestMapping(value = "signup_check", method = { RequestMethod.POST })
	public Map<String, Object> signupCheck(String value) {
		RestResult result = new RestResult();
		User user = userService.queryByUsernameOrEmail(value);
		if (user != null) {
			result.put("valid", false);
			return result.toJsonObject();
		}
		result.put("valid", true);
		return result.toJsonObject();
	}

	@Transactional(rollbackFor = { Exception.class }, readOnly = false)
	@RequestMapping(value = "register", method = { RequestMethod.POST })
	public Map<String, Object> register(String username,String email,String password, String code, HttpSession session) {
		RestResult result = new RestResult();
		if (username == null || email == null || password == null || code == null) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.InvalidParameter));
			return result.toJsonObject();
		}
		if (session.getAttribute("code" + email) == null
				|| !code.equals(String.valueOf(session.getAttribute("code" + email)))) {
			// 短信验证码不正确
			result.setErrorCode(1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.IncorrectSMSVerificationCode));
			return result.toJsonObject();
		}
		
		User user = userService.queryByUsernameOrEmail(username);
		if (user != null) {
			// 已经注册过
			result.setErrorCode(1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.UsernameExist));
			return result.toJsonObject();
		}
		
		user = userService.queryByUsernameOrEmail(email);
		if (user != null) {
			// 已经注册过
			result.setErrorCode(1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.PhoneExist));
			return result.toJsonObject();
		}
		
		// 创建默认组
		Group group = new Group();
		group.setName(username);
		group.setpId(0l);
		groupService.add(group);

		// 新建用户
		user = new User();
		user.setUsername(username);
		user.setEmail(email);
		user.setPassword(password);
		user.setGroupId(group.getId());
		userService.save(user);
		
		// 更新权限表
		List<Role> roles = roleService.queryAll();
		for (Role role : roles) {
			UserRole userRole = new UserRole();
			userRole.setUid(user.getId());
			userRole.setRid(role.getId());
			userRoleService.save(userRole);
		}
		List<Role> basic = roleService.queryBasic();
		for (Role role : basic) {
			UserRole userRole = new UserRole();
			userRole.setUid(user.getId());
			userRole.setRid(role.getId());
			userRoleService.save(userRole);
		}
		// 添加全部设备列表默认列
		TableCustomColumn tcc = new TableCustomColumn();
		List<OrderColumn> columns = new ArrayList<>();
		String columnArr[] = { "type", "name", "status", "model", "softVer","sn","hardwareVer", "group", "uptime","isFast" };
		int orderArr[] = { 1, 2, 4, 5, 6,24,25, 7, 26,28 };
		for (int i = 0; i < columnArr.length; i++) {
			OrderColumn orderColumn = new OrderColumn();
			orderColumn.setColumn(columnArr[i]);
			orderColumn.setOrder(orderArr[i]);
			columns.add(orderColumn);
		}
		tcc.setTableName("devices_all");
		tcc.setColumns(columns);
		tableService.updateCustomColumn(tcc, user.getId());
		
		// 添加ap列表默认列
		tcc = new TableCustomColumn();
		columns = new ArrayList<>();
		String columnArr3[] = { "type", "name", "ip", "status", "model", "softVer", "group", "clients","sn", "uptime" ,"isFast"};
		int orderArr3[] = { 1, 2, 3, 4, 5, 6, 7, 8,24, 26 ,28};
		for (int i = 0; i < columnArr3.length; i++) {
			OrderColumn orderColumn = new OrderColumn();
			orderColumn.setColumn(columnArr3[i]);
			orderColumn.setOrder(orderArr3[i]);
			columns.add(orderColumn);
		}
		tcc.setTableName("devices_ap");
		tcc.setColumns(columns);
		tableService.updateCustomColumn(tcc, user.getId());
		
		// 添加路由设备列表默认列
		tcc = new TableCustomColumn();
		columns = new ArrayList<>();
		String columnArr4[] = { "type", "name", "status", "model", "softVer","sn","hardwareVer", "group", "uptime", "aps","isFast" };
		int orderArr4[] = { 1, 2, 4, 5, 6,24,25, 7, 26, 27,28 };
		for (int i = 0; i < columnArr4.length; i++) {
			OrderColumn orderColumn = new OrderColumn();
			orderColumn.setColumn(columnArr4[i]);
			orderColumn.setOrder(orderArr4[i]);
			columns.add(orderColumn);
		}
		tcc.setTableName("devices_router");
		tcc.setColumns(columns);
		tableService.updateCustomColumn(tcc, user.getId());
		
		// 添加用户状态默认列
		tcc = new TableCustomColumn();
		columns = new ArrayList<>();
		String columnArr1[] = { "hostname", "ip", "mac", "group", "bssid", "ssid", "uptime" };
		int orderArr1[] = { 1, 2, 3, 7, 8, 9, 16 };
		for (int i = 0; i < columnArr1.length; i++) {
			OrderColumn orderColumn = new OrderColumn();
			orderColumn.setColumn(columnArr1[i]);
			orderColumn.setOrder(orderArr1[i]);
			columns.add(orderColumn);
		}
		tcc.setTableName("userstatus");
		tcc.setColumns(columns);
		tableService.updateCustomColumn(tcc, user.getId());
		// 添加历史用户默认列
		tcc = new TableCustomColumn();
		columns = new ArrayList<>();
		String columnArr2[] = { "hostname", "mac", "group", "bssid", "ssid", "uptime" };
		int orderArr2[] = { 1, 2, 6, 7, 8, 11 };
		for (int i = 0; i < columnArr2.length; i++) {
			OrderColumn orderColumn = new OrderColumn();
			orderColumn.setColumn(columnArr2[i]);
			orderColumn.setOrder(orderArr2[i]);
			columns.add(orderColumn);
		}
		tcc.setTableName("history");
		tcc.setColumns(columns);
		tableService.updateCustomColumn(tcc, user.getId());
		
		// 清除session
		session.removeAttribute("code" + email);
		// 注册成功跳转到登录界面
		return result.toJsonObject();
	}

	@RequestMapping(value = "forget", method = { RequestMethod.POST })
	public Map<String, Object> forget(HttpSession session, String email, String password, String code,
			String imageCode) {
		RestResult result = new RestResult();
		if (email == null || password == null || imageCode == null || code == null) {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.InvalidParameter));
			return result.toJsonObject();
		}
		if (session.getAttribute(email) == null
				|| !code.equals(String.valueOf(session.getAttribute(email)))) {
			// 短信验证码不正确
			result.setErrorCode(1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.IncorrectSMSVerificationCode));
			return result.toJsonObject();
		}
		if (!String.valueOf(session.getAttribute("imageCode")).equalsIgnoreCase(imageCode)) {
			// 验证码不正确
			result.setErrorCode(1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.IncorrectVerificationCode));
			return result.toJsonObject();
		}
		User user = userService.queryByUsernameOrEmail(email);
		if (user == null) {
			// 该账号不存在
			result.setErrorCode(1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.PhoneNotExist));
			return result.toJsonObject();
		}
		user.setPassword(password);
		user.setFailtimes((short) 0);
		user.setLastfail(null);
		user.setLastResetDate(new Date());
		userService.update(user);
		// 清除session
		session.removeAttribute(email);
		result.setErrorCode(0);
		result.setErrorMsg(messageSourceUtil.getMessage(Tips.ResetPasswordSuccess));
		// 重置密码成功跳转到登录界面
		Log log = new Log();
		Date date = new Date();
		String ipaddress = SaveIpaddress.getThreadLocal().get();
		log.setIpaddress(ipaddress);
		log.setUserId(user.getId());
		log.setContent(messageSourceUtil.getMessage(Tips.LogRetrievePassword));
		log.setDate(date);
		log.setState(0);
		logService.save(log);
		return result.toJsonObject();
	}

	@RequestMapping(value = "update", method = { RequestMethod.POST })
	public Map<String, Object> update(HttpSession session, Principal principal, String email, String code,
			String oldPasswd, String passwd) {
		RestResult result = new RestResult();
		if (email != null && code != null) {
			
			if (session.getAttribute("updatecode" + email) == null) {
				result.setErrorCode(1);
				result.setErrorMsg(messageSourceUtil.getMessage(Tips.NoVerificationCode));
				return result.toJsonObject();
			}
			if (!code.equals(String.valueOf(session.getAttribute("updatecode" + email)))) {
				result.setErrorCode(3);
				result.setErrorMsg(messageSourceUtil.getMessage(Tips.IncorrectSMSVerificationCode));
				return result.toJsonObject();
			}
			
			User user = userService.queryByUsernameOrEmail(email);
			if (user != null) {
				// 已经注册过
				result.setErrorCode(1);
				result.setErrorMsg(messageSourceUtil.getMessage(Tips.PhoneExist));
				return result.toJsonObject();
			}
			
			Authentication authentication = (Authentication) principal;
			user = (User) authentication.getPrincipal();
			user.setEmail(email);
			user.setLastResetDate(new Date());
			userService.update(user);
			result.setErrorCode(0);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.ResetPasswordSuccess));
			session.removeAttribute("updatecode" + email);
			return result.toJsonObject();
		} else if (oldPasswd != null && passwd != null) {
			Authentication authentication = (Authentication) principal;
			User user = (User) authentication.getPrincipal();
			if (!oldPasswd.equals(user.getPassword())) {
				result.setErrorCode(3);
				result.setErrorMsg(messageSourceUtil.getMessage(Tips.OriginalPasswordFail));
				return result.toJsonObject();
			}
			user.setPassword(passwd);
			user.setLastResetDate(new Date());
			userService.update(user);
			result.setErrorCode(0);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.ResetPasswordSuccess));
			return result.toJsonObject();
		} else if (oldPasswd != null) {
			Authentication authentication = (Authentication) principal;
			User user = (User) authentication.getPrincipal();
			if (!oldPasswd.equals(user.getPassword())) {
				result.setErrorCode(3);
				result.setErrorMsg(messageSourceUtil.getMessage(Tips.OriginalPasswordFail));
				return result.toJsonObject();
			} else {
				return result.toJsonObject();
			}
		} else {
			result.setErrorCode(-1);
			result.setErrorMsg(messageSourceUtil.getMessage(Tips.InvalidParameter));
			return result.toJsonObject();
		}
	}

	@RequestMapping(value = "getInfo", method = { RequestMethod.GET })
	public Map<String, Object> phone(Principal principal) {
		RestResult result = new RestResult();
		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();
		result.put("email", user.getEmail());
		result.put("username", user.getUsername());
		return result.toJsonObject();
	}

	@RequestMapping(value = "editRole", method = { RequestMethod.GET })
	@ResponseBody
	public Map<String, Object> editRole(Principal principal, @RequestParam(value = "names[]") List<String> names) {
		RestResult result = new RestResult();
		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();
		for (String name : names) {
			if (user.hasRole("ROLE_" + name + "_EDIT")) {
				result.put(name, true);
			} else {
				result.put(name, false);
			}
		}
		return result.toJsonObject();
	}

}
